package com.example.library.servlet;

import com.example.library.entity.Book;
import com.example.library.util.BookDao;
import com.example.library.util.impl.BookDaoImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private BookDao bookDao = new BookDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        if ("add".equals(action)){
            String bookId = req.getParameter("bookId");
            String bookName = req.getParameter("bookName");
            String author = req.getParameter("author");
            String publisher = req.getParameter("publisher");
            int publicationYear = Integer.parseInt(req.getParameter("publicationYear"));
            double price = Double.parseDouble(req.getParameter("price"));
            int stock = Integer.parseInt(req.getParameter("stockQuantity"));
            Book book = new Book(bookId,bookName,author,publisher,publicationYear,price,stock);
            bookDao.addBook(book);
            PrintWriter out = resp.getWriter();
            out.println("图书添加成功");
            out.close();
        }else if ("update".equals(action)){

        }else if ("delete".equals(action)){
            String bookId = req.getParameter("bookId");
            bookDao.deleteBook(bookId);
            PrintWriter out = resp.getWriter();
            out.println("图书删除成功");
            out.close();
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String keyword = req.getParameter("keyword");
        List<Book> books = bookDao.getBooks(keyword);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(books);
        PrintWriter out = resp.getWriter();
        out.println(json);
        out.flush();
    }
}
